import * as React from "react";
import { createStyles, makeStyles } from "@material-ui/styles";
import { inject, observer } from "mobx-react";
import { USER } from "../mobx/Stores";
import { User } from "../mobx/data/User";
import { Button } from "antd";
import { useHistory, useLocation } from "react-router"
import Box from "../components/Box";
import { AuthorizationCode, clientId, clientSecret} from "../configs/AuthorizationServer";
import Axios from "axios";

const useStyles = makeStyles(createStyles<"root" | "div", {}>(
    {
      root: {
        marginTop: 20
      },
      div: {}
    }
));

interface Iprops {
  user?: User;
}

/**
 * 描述：
 *  用户信息
 * @author sunshixiong
 * @date 2019/6/26-16:07
 */
const UserInfo: React.FC<Iprops> = (props: Iprops) => {
  const classes = useStyles();
  const location = useLocation();
  const history = useHistory();
  const code = new URLSearchParams(location.search).get("code")
  if (code) {
    Axios.request({
      url: "/oauth/token",
      method: "post",
      params: {
        grant_type: "authorization_code",
        code,
        client_id: clientId,
        client_secret: clientSecret,
        redirect_uri: `${window.location.origin}/`
      },
      baseURL: "/login",
      headers: {
        "authorization": AuthorizationCode,
        "content-type": "application/json"
      }
    }).then(value => {
      window.localStorage.setItem("authToken", value.data.access_token)
      history.push(location.pathname)
    }).catch(reason => {
      console.log(reason)
    })
  }
  return (
      <React.Fragment>
        <div className={ classes.root }>{ props.user!.user }</div>
        <Box border={ 20 } marginTop={ 1 }>孙世雄</Box>
        <Button
            type={ "primary" }
            style={ {border: 20, margin: 10} }
            onClick={ e => {
              props.user!.getData();
            } }
        >
          hello
        </Button>
      </React.Fragment>
  );
};

export default inject(USER)(observer(UserInfo));
